package net.imagine.core;

import java.util.concurrent.Callable;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 执行一张图片的一个操作，需要在构造时传入图片处理任务、图片存放的本地目录、图片处理模板
 * 
 * @see Callable
 * @param <T>
 * @author wuqh
 */
public class ImageProcessTaskExecutor<T extends ImageProcessResult> implements Callable<T> {
	private final Log logger = LogFactory.getLog(getClass());

	protected final String filePath;
	protected final ImageProcessTask task;
	protected final ImageProcessTemplate template;

	/**
	 * 构造方法
	 * 
	 * @param filePath
	 *            图片存放的本地目录
	 * @param task
	 *            图片处理任务
	 * @param template
	 *            图片处理模板
	 */
	public ImageProcessTaskExecutor(String filePath, ImageProcessTask task, ImageProcessTemplate template) {
		this.filePath = filePath;
		this.task = task;
		this.template = template;
	}

	/**
	 * 执行图片处理模板（template）的processImage方法
	 * 
	 */
	@SuppressWarnings("unchecked")
	@Override
	public T call() throws Exception {
		try {
			return template.processImage(filePath, task);
		} catch (Exception e) {
			logger.warn("process image failed", e);
			T result = (T) new ImageProcessResult(ResultState.UNKOWN_FAILED);
			result.setOriginalFilename(task.getFilename());
			return result;
		}
	}
}